//
//  PVDsListSearchViewController.swift
//  GreenDeal
//
//  Created by Moennig Q on 15/12/2022.
//

import UIKit
import RxGesture
import RxSwift
import RxCocoa
import SwiftyJSON
import HandyJSON
class JobsListSearchViewController: BaseViewController {
    fileprivate lazy var disposeBag = DisposeBag()
    var customView: JobsListSearchView!
    var searchModule: SearchModule = .installations
    //total pages for list
    var currentPage: String = "1"
    var nextPage: String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.customView = JobsListSearchView(self.searchModule)
        self.view = customView
        self.customView.toDetailVCClosure = {[weak self](index, operType) in
            guard let strongSelf = self else {return}
            strongSelf.toDetailVC(index,operType: operType)
        }
        if searchModule == .installations{
            self.customView.topView.searchTextfield.placeholder = "GWT NO/SWH NO/Owner Name"
        }else if searchModule == .serviceJobs{
            self.customView.topView.searchTextfield.placeholder = "Number/Job Title"
        }
        self.customView.topView.cancelLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.navigationController?.popViewController(animated: true)
        }).disposed(by: self.disposeBag)
        self.customView.topView.searchTextfield.rx.controlEvent(.editingDidEndOnExit).subscribe { [weak self] _ in
            guard let strongSelf = self else {return }
            guard let searchText = strongSelf.customView.topView.searchTextfield.text , searchText.trimmingCharacters(in: .whitespaces) != "" else {return}
            if strongSelf.searchModule == .installations{
                strongSelf.loadInstallationList()
            }else{
                strongSelf.loadServiceJobsList()
            }
        }.disposed(by: self.disposeBag)
    }
    /// 点击跳转
    private func toDetailVC(_ index: Int, operType: PVDsListCellOperType? = nil){
        if self.searchModule == .installations{
            guard let model = self.customView.dataObserver.value[index] as? InstallationListModel else {return}
            
            JobDetailModelHelper.shared.jobDetailModel = PVDDetailModel()
            JobDetailModelHelper.shared.jobDetailModel.pvd_id = model.pvd_id
            //记录Crash log时的pvd id和gwt id
            SentryHelper().setCrashLogCustomInfo(pvdId: model.pvd_id ,gwtNo: model.gwt_id)
            JobDetailModelHelper.shared.jobDetailModel.gwt_id = model.gwt_id
            JobDetailModelHelper.shared.jobDetailModel.owner_address.type_name = model.full_name
            if model.solar_water_heater {//swh
                let vc = SWHDetailViewController()
                vc.reloadPVDsListClosure = {[weak self] in
                    guard let strongSelf = self else { return  }
                    strongSelf.loadInstallationList(loadingFlag: false)
                    
                }
                switch operType {
                case .barcode:
                    vc.skipToWhere = .Barcode
                case .checklist:
                    vc.skipToWhere = .Checklist
                case .signature:
                    vc.skipToWhere = .Signature
                default:
                    break
                }
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: false)
            }else{//solar
                let vc = JobDetailViewController()
                vc.reloadPVDsListClosure = {[weak self] in
                    guard let strongSelf = self else { return  }
                    strongSelf.loadInstallationList(loadingFlag: false)
                    
                }
                switch operType {
                case .barcode:
                    vc.skipToWhere = self.skipToWhereFoBarcode(model)
                case .checklist:
                    vc.skipToWhere = .Checklist
                case .signature:
                    vc.skipToWhere = .Signature
                case .cesfile:
                    vc.skipToWhere = .CESFile
                default:
                    break
                }
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: false)
            }
            
        }else if self.searchModule == .serviceJobs{
            guard let model = self.customView.dataObserver.value[index] as? ServiceJobListModel else {return}
            let vc = ServiceJobDetailViewController()
            vc.hidesBottomBarWhenPushed = true
            vc.reloadServiceJobsListClosure = {[weak self] in
                guard let strongSelf = self else { return  }
                strongSelf.loadServiceJobsList(loadingFlag: false)
            }
            ServiceDetailModelHelper.shared.serviceDetailModel = ServiceDetailModel()
            ServiceDetailModelHelper.shared.serviceDetailModel.id = model.id
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
    private func skipToWhereFoBarcode(_ model: InstallationListModel)->SkipToWhere{
        var toWhere: SkipToWhere = .Panel
        let panelCnt = (model.new_panel_number_count)
        let panelFinishCnt = (model.new_panel_number_finished_count)
        let inverterCnt = (model.inverter_number_count)
        let inverterFinishCnt = (model.inverter_number_finished_count)
        if model.is_new_stc_form && panelCnt <= panelFinishCnt && inverterCnt > inverterFinishCnt{//安装日期在2022-04-01以后的Job才这样处理，panel数量已经扫够，inverter数量不够，就跳转到Inverter，其他情况跳转到Panel
            toWhere = .Inverter
        }
        return toWhere
    }
    //MARK: - 根据GWTID查找installation list
    private func loadInstallationList(loadingFlag: Bool = true){
        //set block
        let vm = JobsListService()
        vm.setBlockAfterNetwork({ (result, otherInfo) -> Void in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            
            //header data
            if let data = otherInfo?.object(forKey: "X-Next-Page") as? String{
                self.nextPage = data
            }else{
                self.nextPage = ""
            }
            //data list
            guard let res = result else {return}
            let json = JSON(res)
            if let data = JSONDeserializer<InstallationListModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<InstallationListModel>{
                if self.currentPage == "1" {
                    self.customView.dataObserver.accept(data)
                }else{
                    let temp = data
                    self.customView.dataObserver.accept(self.customView.dataObserver.value + temp)
                }
                //没有数据显示not data view，有数据隐藏not data view
                self.customView.tableView.showResultView(nodataFlag: self.customView.dataObserver.value.count == 0 ? true : false)
            }
        }) { (code, error) -> Void in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            
            Tool().showErrorInfo(code, error)
        }
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView()
        }
        
        let combineStr = "?page=\(self.currentPage)&gwt_id=" + (self.customView.topView.searchTextfield.text ?? "")
        vm.getInstallationsListForV2(combineStr)
    }
    //MARK: - 根据title或user name查找service list
    private func loadServiceJobsList(loadingFlag: Bool = true){
        //set block
        let vm = MyBidJobsListViewModel()
        vm.setBlockAfterNetwork{ result, otherInfo in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }

            //header data
            self.nextPage = otherInfo?.object(forKey: "X-Next-Page") as? String ?? ""
            guard let res = result else {return}
            let json = JSON(res)
            if let data = JSONDeserializer<ServiceJobListModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<ServiceJobListModel>{
                if self.currentPage == "1" {
                    self.customView.dataObserver.accept(data)
                }else{
                    let temp = data
                    self.customView.dataObserver.accept(self.customView.dataObserver.value + temp)
                }
                //没有数据显示not data view，有数据隐藏not data view
                self.customView.tableView.showResultView(nodataFlag: self.customView.dataObserver.value.count == 0 ? true : false)
            }
        } errorBlock: { code, error in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            Tool().showErrorInfo(code, error)
        }
        
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView()
        }
        //add Loading view
        let combineStr = "?page=\(self.currentPage)&title=" + (self.customView.topView.searchTextfield.text ?? "")
        vm.getMyBidJobsList(combineStr)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
}
